<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue';
import { getIngredientsList, addIngredients, updateIngredients, deleteIngredients } from '@/api/ingredients';
import type { Page } from '@/api/types/page';
import type { Ingredients, IngredientsSearchParam } from '@/api/ingredients/types';
const queryFormRef = ref()
const queryForm = ref<IngredientsSearchParam>({
    pageNum: 1,
    pageSize: 5,
    name: '',
    type: ''
})
const total = ref(0)
const ingredientsList = ref<Ingredients[]>([])

const listIngredients = (pageNum = 1) => {
    queryForm.value.pageNum = pageNum
    getIngredientsList(queryForm.value).then((page: Page<Ingredients>) => {
        total.value = page.total
        ingredientsList.value = page.rows
    }).catch(e => {
        console.log(e)
    })
}
const base_url = import.meta.env.VITE_APP_BASE_API
import { useDict } from '@/util/useDict';
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus';
import { fa } from 'element-plus/es/locales.mjs';
const { dict, showDicName } = useDict('ingredients')

const ingredientsFormVisible = ref(false)
const ingredientsFormTitle = ref('添加食材')
const ingredientsFormRef = ref()
const ingredientsForm = ref<Ingredients>({
    name: '',
    type: '',
    url: '',
    description: ''
})
const ingredientsFormRules = ref<FormRules>({
    name: [{ required: true, message: '请输入菜品名称' }],
    type: [{ required: true, message: '亲选择菜品类型' }],
    url: [{ required: true, message: '请上传图片' }],
    description: [{ required: true, message: '请输入菜品描述' }]
})


onMounted(() => {
    listIngredients()
})
const resetQueryForm = () => {
    queryFormRef.value.resetFields()
    listIngredients()
}
const addIngredientsForm = () => {
    ingredientsFormVisible.value = true
    nextTick(() => {
        ingredientsFormTitle.value = '添加食材'
        ingredientsForm.value = {
            name: '',
            type: '',
            url: '',
            description: ''
        }
        fileList.value = []
        ingredientsFormRef.value.resetFields()
    })
}
/**上传 */
const fileList = ref([])
const fileLimit = ref(1)
//上传成功方法
const handleUploadSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    ingredientsForm.value.url = response.data
    ingredientsFormRef.value.validate('url')
}
const handleRemove: UploadProps['onRemove'] = (file, files) => {
    ingredientsForm.value.url = ''
    fileList.value = []
    ingredientsFormRef.value.validate('url')
}
const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPG = rawFile.type == 'image/jpeg'
    const isPNG = rawFile.type == 'image/png'
    console.log(rawFile.type)
    const isLt1MB = rawFile.size / 1024 / 1024 < 1
    if (!isJPG && !isPNG) {
        ElMessage.warning('仅支持png/jpg格式')
        return false
    }
    if (!isLt1MB) {
        ElMessage.warning('文件大小不能超过1mb')
        return false
    }

}
const handleExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning(
        '不能超过一张图片'
    )

}
const submitIngredientForm = () => {
    ingredientsFormRef.value.validate(async (v: boolean) => {
        if (v) {
            if (!ingredientsForm.value.id) {
                await addIngredients(ingredientsForm.value)
                queryForm.value.pageNum = 1
                ElMessage.success('添加成功！')

            } else {
                await updateIngredients(ingredientsForm.value.id, ingredientsForm.value)
                ElMessage.success('修改成功！')
            }

            listIngredients(queryForm.value.pageNum)
            ingredientsFormVisible.value = false
            ingredientsForm.value = {
                name: '',
                type: '',
                url: '',
                description: ''
            }
            fileList.value = []
            ingredientsFormRef.value.resetFields()

        }
    })
}

/**修改删除 */
const update = (row: any) => {
    ingredientsFormVisible.value = true

    nextTick(() => {
        ingredientsFormTitle.value = '修改'
        ingredientsForm.value = { ...row }
        fileList.value = [{ name: row.url, url: base_url + row.url }]
    })
}
const del = async (id: number) => {
    await deleteIngredients(id)
    ElMessage.success('删除成功')
    listIngredients()
}
</script>

<template>
    <div class="app-container">
        <el-form :model="queryForm" ref="queryFormRef" inline>
            <el-form-item label="食材名称" prop="name">
                <el-input v-model="queryForm.name" placeholder="请输入食材名称"></el-input>
            </el-form-item>
            <el-form-item label="食材类型" prop="type">
                <el-select v-model="queryForm.type" placeholder="请选择" clearable style="width: 180px;">
                    <el-option v-for="item in dict['ingredients']" :key="item.id" :label="item.name"
                        :value="item.value"></el-option>
                </el-select>

            </el-form-item>
            <el-form-item>
                <el-button type="primary" plain icon="Search" @click="listIngredients()">搜索</el-button>
                <el-button type="info" plain icon="Refresh" @click="resetQueryForm()">重置</el-button>
                <el-button type="success" plain icon="Plus" @click="addIngredientsForm()">添加</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="ingredientsList" border stripe style="width: 100%;">
            <el-table-column type="index" label="编号" width="80px" align="center"></el-table-column>
            <el-table-column label="食材名称" prop="name" align="center"></el-table-column>
            <el-table-column label="食材类型" align="center">
                <template #default="{ row }">
                    <el-tag>{{ showDicName('ingredients', row.type) }}</el-tag>
                </template>

            </el-table-column>
            <el-table-column label="食材图片" align="center">
                <template #default="{ row }">
                    <el-image :src="base_url + row.url" style="width: 60px;height: 60px;"
                        :preview-src-list="[base_url + row.url]" preview-teleported></el-image>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" plain icon="Edit" @click="update(scope.row)">修改</el-button>
                    <el-button type="danger" plain icon="Delete" @click="del(scope.row.id)">删除</el-button>
                </template>

            </el-table-column>

        </el-table>
        <el-pagination style="margin-top:10px ;" :total="total" layout="total,sizes,prev,pager,next,jumper" background
            :page-sizes="[5, 10, 50]" v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
            @current-change="listIngredients" @size-change="listIngredients()"></el-pagination>
        <el-dialog v-model="ingredientsFormVisible" :title="ingredientsFormTitle" width="600"
            :close-on-click-modal="false">
            <el-form :model="ingredientsForm" ref="ingredientsFormRef" :rules="ingredientsFormRules">
                <el-form-item prop="name" label="菜品名称">
                    <el-input v-model="ingredientsForm.name" placeholder="请输入菜品名称"></el-input>
                </el-form-item>
                <el-form-item prop="url">
                    <el-upload v-model:file-list="fileList" class="upload-demo"
                        :action="base_url + '/dishes-service/upload/image'" :on-success="handleUploadSuccess"
                        :on-exceed="handleExceed" :before-upload="handleBeforeUpload" :on-remove="handleRemove"
                        :limit="fileLimit" list-type="picture">
                        <el-button type="primary">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                仅支持pngjpg格式 大小不超过1M
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item prop="type" label="食材类型">
                    <el-radio-group v-model="ingredientsForm.type">
                        <el-radio v-for="item in dict['ingredients']" :key="item.id" :label="item.name"
                            :value="item.value"></el-radio>

                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="description" label="菜品描述">
                    <el-input type="textarea" v-model="ingredientsForm.description" placeholder="请输入菜品描述信息"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="ingredientsFormVisible = false">取消</el-button>
                    <el-button type="primary" @click=submitIngredientForm>
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style>
.el-upload-list__item {
    transition: none !important;
    -webkit-transition: nonne !important;
}

.el-upload-list__item-name {
    transition: none !important;
    -webkit-transition: nonne !important;
}
</style>